//
//  LTTicketOrderController.m
//  LocalTravelIPhone
//
//  Created by zheng ji on 14-3-30.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTTicketOrderController.h"

@interface LTTicketOrderController ()
{
    CKCalendarView* _calendar;
    double _tcPrice;
    double _price;
    NSString* _policyId;
    BOOL _needIdCard;// 是否需要身份证号码
    int _maxT; //最大预订张数
    int _minT;//最少预订张数
    int _beforeDays;//提前天数
    NSString* _sceneryId;
    UIActivityIndicatorView *_activityView;
    UILabel* _loadMoreTip;
}
@end

@implementation LTTicketOrderController
- (IBAction)textFieldDidEndOnExit:(UITextField *)sender {
    [sender resignFirstResponder];
}

- (IBAction)tracelDateSelect:(UITextField *)sender {
    [sender becomeFirstResponder];
    [sender resignFirstResponder];
    
    if(_calendar==nil){
        _calendar = [[CKCalendarView alloc] initWithStartDay:startMonday];
        _calendar.frame = CGRectMake(sender.frame.origin.x-20, sender.frame.origin.y+60 , 250, 450);
        _calendar.delegate=self;
        [self.view addSubview:_calendar];
    }else{
        _calendar.hidden=NO;
    }
 [sender resignFirstResponder];
}

- (void)calendar:(CKCalendarView *)calendar didSelectDate:(NSDate *)date{
    NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    fmt.dateFormat = @"yyyy-MM-dd";
    self.textFieldDate.text = [fmt stringFromDate:date];
    
    _calendar.hidden=YES;
    [self.textFieldDate resignFirstResponder];
    
    
}


- (IBAction)stepperValueChanged:(UIStepper *)sender {
    self.textFieldCount.text=[NSString stringWithFormat:@"%.f",sender.value];
    
    double count=[self.textFieldCount.text doubleValue];
    self.lblPriceTotal.text=[NSString stringWithFormat:@"总额 %.2f",_tcPrice*count];
    self.lblJieYue.text=[NSString stringWithFormat:@"节约：%.2f",count *(_price - _tcPrice)];
}
- (IBAction)submitOrder:(UIBarButtonItem *)sender {
  
    
    NSString* bMan=[self.lblName.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //NSString* t=self.lblPhoneNumber.text;
    NSString* bMobile=[self.lblPhoneNumber.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* tName=bMan;
    NSString* tMobile=bMobile;
    //NSString* policyId=_policyId;
    NSString* tickets=[self.textFieldCount.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* travelDate=[self.textFieldDate.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSString* idCard=[self.lblIdCard.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if(travelDate==nil ||[travelDate  isEqualToString:@""]){
        self.lblResultTip.text=@"请选择游玩日期！";
        return ;
    }
    if(bMan==nil || [bMan  isEqualToString:@""]){
        self.lblResultTip.text=@"请输入取票人姓名！";
        return ;
    }
    if(bMobile==nil ||[bMobile  isEqualToString:@""]){
        self.lblResultTip.text=@"请输入手机号码！";
        return ;
    }else if(bMobile.length!=11){
        
        self.lblResultTip.text=@"请输入正确的手机号码！";
        return ;
        
        
    }else{
        NSString* strM = [bMobile stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
        if(strM.length != 0)
        {
            self.lblResultTip.text=@"请输入正确的手机号码！";
            return ;
        }
        
    }
    if(tickets==nil ||[tickets  isEqualToString:@""]){
        self.lblResultTip.text=@"请输入预订张数！";
        return ;
    }
    
  
    
    if(_maxT >0){
        if([tickets intValue]>_maxT){
            self.lblResultTip.text=[NSString stringWithFormat:@"最大预订张数：%d",_maxT];
        }
    }
    if(_minT >0){
        if([tickets intValue]<_minT){
            self.lblResultTip.text=[NSString stringWithFormat:@"最少预订张数：%d",_minT];
        }
    }
    
    if(_beforeDays>0){
        
        NSDateFormatter* fmt = [[NSDateFormatter alloc] init];
        fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
        fmt.dateFormat = @"yyyy-MM-dd";
        
        NSDate* selectedDate=[fmt dateFromString:travelDate];
        NSDate *now=[[NSDate alloc]init];
        
        now= [now dateByAddingTimeInterval:(24*60*60*_beforeDays)];
        
        if([selectedDate compare:now]==NSOrderedAscending){
            self.lblResultTip.text=[NSString stringWithFormat:@"须提前：%d天预订",_beforeDays];
            return;
        }
        
    }
    idCard=@"";
    NSDictionary* dictRequest=[NSDictionary dictionaryWithObjectsAndKeys:_sceneryId,@"sceneryId", bMan,@"bMan",bMobile,@"bMobile",tName,@"tName",tMobile,@"tMobile",_policyId,@"policyId",tickets,@"tickets",travelDate,@"travelDate",idCard,@"idCard",nil];
    
    [self createActivityIndicatorView];
    [NSThread detachNewThreadSelector:@selector(processOrderInBackground:) toTarget:self withObject:dictRequest];
    
}

-(void)processOrderInBackground:(NSDictionary*)dictRequest{
    NSDictionary* dictReturn=  [SceneryOrderRequest submitOrder:dictRequest];
    
    NSString* rspCode=[dictReturn objectForKey:@"rspCode" ];
    if(rspCode !=nil && [rspCode isEqualToString:@"0000"]){
        //成功
        self.lblResultTip.text=@"预订成功，请注意查收手机短信。";
    }else{
        self.lblResultTip.text=[NSString stringWithFormat:@"预订失败，%@",[dictReturn objectForKey:@"rspDesc" ]];
    }
    [self stopActivityIndicatorView];

}

-(void)showTicket{
    self.lblResultTip.text=@"";
    
    _sceneryId=[self.dictParam objectForKey:@"sceneryId"];
    NSString* useCard=[self.dictParam objectForKey:@"useCard"];
    if(useCard !=nil && [useCard isEqualToString:@"1"]){
        
        _needIdCard=YES;
        self.lblIdCard.placeholder=@"用于景区取票";
    }else{
        _needIdCard=NO;
        
        self.lblIdCard.placeholder=@"可选择";
        
    }

    
    NSDictionary* dict=[self.dictParam objectForKey:@"ticket"];
    
    self.lblTicketName.text=[dict objectForKey:@"policyName"];
    _policyId=[dict objectForKey:@"policyId"];
    
   // self.lblDescription.text=[NSString stringWithFormat:@"说明：\r\n\r\n%@ \r\n \r\n取票地点：\r\n\r\n%@",[dict objectForKey:@"remark"],[dict objectForKey:@"gMode"]];
    self.lblPrice.text=[NSString stringWithFormat:@"¥：%@",[dict objectForKey:@"tcPrice"] ];
    _tcPrice=[[dict objectForKey:@"tcPrice"] doubleValue ];
    _price=[[dict objectForKey:@"price"] doubleValue ];
    
    
    
    NSString* strMinT=[dict objectForKey:@"minT"];
    NSString* strMaxT=[dict objectForKey:@"maxT"];
    
    if(strMaxT !=nil && ![strMaxT isEqualToString:@""]){
        _maxT=[strMaxT intValue];
    }
    if(strMinT !=nil && ![strMinT isEqualToString:@""]){
        _minT=[strMinT intValue];
    }
    if(_minT==0) _minT=1;
    
    self.textFieldCount.text=[NSString stringWithFormat:@"%d",_minT];
    
    
    double count=[self.textFieldCount.text doubleValue];
    
    
    self.lblPriceTotal.text=[NSString stringWithFormat:@"总额：%.2f",count * _tcPrice];
    self.lblJieYue.text=[NSString stringWithFormat:@"节约：%.2f",count *(_price - _tcPrice)];
    NSString* date=[self.dictParam objectForKey:@"day"];
    NSString* time=[self.dictParam objectForKey:@"time"];
    
    NSMutableString* buffer=[[NSMutableString alloc]init];
    if(date !=nil && ![date isEqualToString:@""]){
        [buffer appendFormat:@"须提前%@天",date];
        _beforeDays=[date intValue];
    }
    if(time !=nil && ![time isEqualToString:@""]){
        [buffer appendFormat:@"[%@前]",time];
    }
    
    self.lblTips.text=[NSString stringWithFormat:@"温馨提示：本票型%@ 预订张数限制%@-%@张。订单提交成功后，您将收到同程网的订单确认短信。凭此短信直接到同程指定的售票窗口取票。",buffer,[dict objectForKey:@"minT"],[dict objectForKey:@"maxT"]];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor=BACKGROUND_COLOR;
    [self showTicket];
}
-(void)stopActivityIndicatorView{
    [_activityView stopAnimating];
    [_activityView removeFromSuperview];
    _loadMoreTip.hidden=YES;
    [_loadMoreTip removeFromSuperview];
    
}
-(void)createActivityIndicatorView{
    _activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityView.hidesWhenStopped=YES;
    CGRect activityFrame=_activityView.frame;
    activityFrame.origin.x=self.view.frame.size.width/2-50;
    activityFrame.origin.y=self.view.frame.size.height/2-100;
    
    [_activityView setFrame:activityFrame];
    
    _activityView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    
    
    
    _loadMoreTip=[[UILabel alloc] initWithFrame:CGRectMake(activityFrame.origin.x+30, activityFrame.origin.y+5, 100, 20)];
    
    _loadMoreTip.textAlignment=NSTextAlignmentCenter;
    
    _loadMoreTip.text=@"正在加载数据";
    _loadMoreTip.textColor=[UIColor redColor];
    _loadMoreTip.font=[UIFont systemFontOfSize:16];
    _loadMoreTip.backgroundColor=[UIColor clearColor];
    
    [self.view addSubview:_activityView];
    [self.view addSubview:_loadMoreTip];
    [_activityView startAnimating];
    _activityView.hidden=NO;
    _loadMoreTip.hidden=NO;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
